﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Common
{
    public static class PagingHelper
    {
        /// <summary>
        /// 首尾是第一和最后一页
        /// </summary>
        /// <param name="count">数据总数</param>
        /// <param name="pageSize">每页显示数据</param>
        /// <param name="index">当前所在页面</param>
        /// <param name="url"></param>
        /// <param name="showCount">显示分页数量</param>
        public static string PagingRaw(int count, int pageSize, int index, string url, int showCount)
        {
            int leftCount = (showCount - 1) / 2;
            int rightCount = (showCount - 1) / 2;

            if ((rightCount - 1) % 2 == 0)
            {
                rightCount += 1;
            }

            int pageCount = count % pageSize == 0 ? count / pageSize : count / pageSize + 1;
            if (index > pageCount)
            {
                index = pageCount;
            }
            string strPaging = "<ul class=\"pagination\">";

            int i = 1;
            int j = pageCount;

            if (index - leftCount > 0)
            {
                i = index - leftCount;
                j = index + rightCount;
            }
            else
            {
                j = index + (leftCount + rightCount + 1) - index;
            }
            if (j > pageCount)
            {
                j = pageCount;
            }
            if ((pageCount - index) < rightCount)
            {
                i = i - (rightCount - (pageCount - index));
                if (i <= 0)
                {
                    i = 1;
                }
            }


            string tempurl = string.Empty;
            if (index > 1)
            {
                tempurl = string.Format(url, 1);
                strPaging += $"<li><a href='{tempurl}'>«</a></li>";
            }

            for (int k = i; k <= j; k++)
            {
                if (k != index)
                {
                    tempurl = string.Format(url, k);
                    strPaging += $"<li><a href='{tempurl}'>{k}</a></li>";
                }
                else
                {
                    strPaging += $"<li class=\"active\"><a href=\"javascript:;\">{k}</a></li>";
                }
            }
            if (index < pageCount)
            {
                tempurl = string.Format(url, pageCount);
                strPaging += $"<li><a href='{tempurl}'>»</a></li>";
            }
            strPaging += "</ul>";
            return strPaging;
        }
    }
}
